import 'package:flutter/material.dart';

class AlignedNotebookPage extends StatefulWidget {
  const AlignedNotebookPage({Key? key}) : super(key: key);

  @override
  _AlignedNotebookPageState createState() => _AlignedNotebookPageState();
}

class _AlignedNotebookPageState extends State<AlignedNotebookPage> {
  final TextEditingController _controller = TextEditingController();
  final FocusNode _focusNode = FocusNode();

  // 配置参数
  final double _lineHeight = 32.0; // 理想行高
  final double _marginLeft = 40.0;
  final Color _lineColor = Colors.grey.withOpacity(0.3);
  final Color _paperColor = Colors.yellow[50]!;
  final double _textScaleFactor = 1.0;

  // 文本样式
  late TextStyle _textStyle;
  late double _actualLineHeight;
  late double _textTopOffset;

  @override
  void initState() {
    super.initState();
    _initializeTextStyle();
  }

  void _initializeTextStyle() {
    // 创建文本样式并计算实际行高
    _textStyle = const TextStyle(
      fontSize: 18.0,
      height: 1.0, // 基于字体大小的行高比例
    );

    // 使用TextPainter计算实际行高和偏移
    final TextPainter textPainter = TextPainter(
      text: TextSpan(text: 'A', style: _textStyle),
      textDirection: TextDirection.ltr,
      textScaleFactor: _textScaleFactor,
    )..layout(minWidth: 0, maxWidth: double.infinity);

    // 计算实际行高和文本顶部偏移
    _actualLineHeight = textPainter.height;
    // - textPainter.descent
    _textTopOffset = textPainter.height;

    // 调整行高以匹配期望的视觉效果
    _textStyle = _textStyle.copyWith(
      height: _lineHeight / _actualLineHeight,
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('对齐笔记本'),
        actions: [
          IconButton(
            icon: const Icon(Icons.save),
            onPressed: () => _saveNote(),
          ),
        ],
      ),
      body: Container(
        decoration: BoxDecoration(
          color: _paperColor,
          boxShadow: [
            BoxShadow(
              color: Colors.grey.withOpacity(0.5),
              spreadRadius: 2,
              blurRadius: 5,
              offset: const Offset(0, 3),
            ),
          ],
        ),
        child: Stack(
          children: [
            // 背景横线和装订线
            CustomPaint(
              size: Size.infinite,
              painter: AlignedNotebookPainter(
                lineHeight: _lineHeight,
                lineColor: _lineColor,
                marginLeft: _marginLeft,
                textTopOffset: _textTopOffset,
              ),
            ),
            // 文本输入区域 - 精确控制内边距
            Padding(
              padding: EdgeInsets.only(
                left: _marginLeft + 8.0,
                right: 16.0,
                top: _textTopOffset + 4.0, // 顶部偏移以确保文本与横线对齐
              ),
              child: TextField(
                controller: _controller,
                focusNode: _focusNode,
                maxLines: null,
                style: _textStyle,
                decoration: const InputDecoration(
                  border: InputBorder.none,
                  hintText: '开始输入...',
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _saveNote() {
    // 实现笔记保存逻辑
    final String text = _controller.text;
    if (text.isNotEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('笔记已保存')),
      );
    }
  }
}

class AlignedNotebookPainter extends CustomPainter {
  final double lineHeight;
  final Color lineColor;
  final double marginLeft;
  final double textTopOffset;

  AlignedNotebookPainter({
    required this.lineHeight,
    required this.lineColor,
    required this.marginLeft,
    required this.textTopOffset,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final Paint linePaint = Paint()
      ..color = lineColor
      ..strokeWidth = 1.0;

    // 计算行数
    final int lineCount = (size.height / lineHeight).ceil();

    // 绘制横线，考虑文本偏移
    for (int i = 0; i < lineCount; i++) {
      final double y = lineHeight * (i + 1) - textTopOffset;
      canvas.drawLine(
        Offset(marginLeft, y),
        Offset(size.width, y),
        linePaint,
      );
    }

    // 绘制装订线
    final Paint marginPaint = Paint()
      ..color = Colors.grey.withOpacity(0.5)
      ..strokeWidth = 2.0;

    canvas.drawLine(
      Offset(marginLeft / 2, 0),
      Offset(marginLeft / 2, size.height),
      marginPaint,
    );

    // 绘制顶部阴影
    final Paint shadowPaint = Paint()
      ..color = Colors.black.withOpacity(0.1)
      ..maskFilter = const MaskFilter.blur(BlurStyle.normal, 3.0);

    canvas.drawRect(
      Rect.fromLTRB(0, 0, size.width, 5),
      shadowPaint,
    );
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
